import { utilDateToChinese } from '@/utils';

/*
 * @desc: 金额数字使用逗号格式化
*/
export const moneyToComma = (value, digits = 2) => {
  let values = String(parseFloat((String(value)).replace(/[^\d\.-]/g, '')).toFixed(digits));
  let l = values.split('.')[0].split('').reverse();
  let r = values.split('.')[1];
  let t = '';
  for (let i = 0; i < l.length; i++) {
    t += l[i] + ((i + 1) % 3 === 0 && (i + 1) !== l.length ? ',' : '');
  }
  return t.split('').reverse().join('') + '.' + r;
};

/*
 * @desc: 分转元
*/
export const fenToyuan = (value, digits = 0) => {
  // 检查金额格式
  if (!/^[1-9]\d*$/.test(String(value))) return '0';
  // 保留1到2位小数
  const oriYuan = (value / 100);
  if ([1, 2].includes(digits)) {
    return oriYuan.toFixed(digits);
  }
  const baseOriYuan = oriYuan.toFixed(2);
  if (/^\d+\.\d[0]$/.test(baseOriYuan)) {
    return baseOriYuan.toFixed(1);
  } else if (/^\d+\.[0][0]$/.test(baseOriYuan)) {
    return parseInt(baseOriYuan, 10);
  } else {
    return baseOriYuan;
  }
};

/*
 * @desc: 手机号码脱敏
*/
export const desensitization = (value) => {
  if (String(value).length !== 11) return '';
  return String(value).substring(0, 3) + '****' + String(value).substr(value.length - 4);
};

/*
 * @desc: 时间格式转年月日
*/
export const dateToChinese = (value) => {
  return utilDateToChinese(value);
};

/*
 * @desc: 时间格式转年月日
*/
export const countdown = (SEC) => {
  if (SEC <= 0) {
    return '00h00m00s'
  }
  let sec = Math.floor(SEC % 60);
  let min = Math.floor(SEC / 60 % 60);
  let hour = Math.floor(SEC / 60 / 60 % 24);
  let day = Math.floor(SEC / 60 / 60 / 24);

  sec = sec > 9 ? sec : `0${sec}`;
  min = min > 9 ? min : `0${min}`;
  hour = hour > 9 ? hour : `0${hour}`;

  if (day > 0) {
    return `${day * 24 + Number(hour)}h${min}m${sec}s`;
  } else {
    return `${hour}h${min}m${sec}s`;
  }
};

/*
 * @desc: 钱包地址脱敏
*/
export const addrdesen = (value) => {
  if (String(value).length < 8) return value;
  if (String(value).substring(0, 1) !== 'T') return value;
  return String(value).substring(0, 4) + '****' + String(value).substr(value.length - 4);
};

/*
 * @desc: 保留3位小数
*/
export const wei3 = (value) => {
  return parseFloat(value).toFixed(3);
};

export default [
  { key: 'moneyToComma', filterFun: moneyToComma },
  { key: 'fenToyuan', filterFun: fenToyuan },
  { key: 'desensitization', filterFun: desensitization },
  { key: 'dateToChinese', filterFun: dateToChinese },
  { key: 'countdown', filterFun: countdown },
  { key: 'addrdesen', filterFun: addrdesen },
  { key: 'wei3', filterFun: wei3 }
];